<?php

/**
 * Description of UserController
 *
 * @author Ho Huu Tai <hohuutai.uns@gmail.com>
 */
class UserController extends BaseController
{

    public $layout = '//layouts/main';

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // deny all users
                'actions' => array('active', 'reset', 'renewpassword'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('confirmwithdraw','chiahoahong','ref_list','partialprofile','profile', 'statistic', 'changepass', 'deposit', 'withdraw', 'introduce_ref'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Update user profile
     */
    public function actionProfile()
    {
    //	echo Yii::app()->user->id;
    	//echo $_REQUEST['lr_encrypted'].'===='.$_REQUEST['lr_encrypted2'].'<---';
        if(isset($_REQUEST['lr_paidto']) && $_REQUEST['lr_paidto'] == Constant::LR_ACC_ID)
        {
            Yii::app()->user->setFlash('lr_deposit_message', 'Nạp tiền vào tài khoản thành công, cảm ơn bạn đã sử dụng dịch vụ vietlode.com ;)');
        }
        $sql = "SELECT user_name, DATE_FORMAT(date_reg,'%W, %H:%i:%s %d/%m/%Y') as date_reg, lr_acc, lr_money, email, DATE_FORMAT(last_login, '%W, %H:%i:%s %d/%m/%Y') as last_login, last_ip
                FROM ld_user WHERE user_id=:user_id";
        $model = User::model()->findBySql($sql, array(':user_id' => Yii::app()->user->id));
        $this->render('user_profile', array('model' => $model));
    }
    
    /*
     * Chia hoa hong
     */
    
    public function actionChiahoahong(){
    	$user=User::model()->find('user_id=:user_id',array(':user_id'=>Yii::app()->user->id));
    	$string=$user->ref_id;
    	$string=substr($string,1,strlen($string));
    	$string='('.$string.')';
    	
    	
    	$users = Yii::app()->db->createCommand()
    	->select('sum(last_section_spent) as abc')
    	->from('ld_user')
    	->where('user_id in '.$string)
    	->queryrow();  
    	$user->lr_khuyenmai+=round($users['abc'],0,PHP_ROUND_HALF_DOWN)/50;	
    	$user->ref_money+=round($users['abc'],0,PHP_ROUND_HALF_DOWN)/50;	
    	if ($user->save())
    	{
    		
    		$update=Yii::app()->db->createCommand('update ld_user set last_section_spent=0
    				where user_id in '.$string)->query();
    		//print_r($update);
    		$this->render('chiahoahong',$users);
    		
    	}
    	//exit($string.'aaaa'.round($users['abc'],0,PHP_ROUND_HALF_DOWN));
    }
    
    /*
     *  List of user whom i referred
     */
    
    public function actionref_list()
    {
    	$user=User::model()->find('user_id=:user_id',array(':user_id'=>Yii::app()->user->id));
    	$string=$user->ref_id;
    	if ($string==null)
    	{
    		$this->render('no_ref_list');
    		exit;
    	}

    	$string=substr($string,1,strlen($string));
    	$string='('.$string.')';
    	//echo $string;
    	
    	$data=array();
        $users = Yii::app()->db->createCommand()
                ->select('user_id,user_name,last_section_spent,total_spent')
                ->from('ld_user')
                ->where('user_id in '.$string)
                ->queryAll();
        $data['users'] = $users;
    	$this->render('ref_list',$data);
		
    }
/*
 *  show profile partially
 */    
    public function actionPartialProfile()
    {
    	if(isset($_REQUEST['lr_paidto']) && $_REQUEST['lr_paidto'] == Constant::LR_ACC_ID)
    	{
    		Yii::app()->user->setFlash('lr_deposit_message', 'Nạp tiền vào tài khoản thành công, xin vui lòng kiểm tra lại ;)');
    	}
    	$sql = "SELECT user_name, DATE_FORMAT(date_reg,'%W, %H:%i:%s %d/%m/%Y') as date_reg, lr_acc, lr_money, lr_khuyenmai, email, DATE_FORMAT(last_login, '%W, %H:%i:%s %d/%m/%Y') as last_login, last_ip
    	FROM ld_user WHERE user_id=:user_id";
    	$model = User::model()->findBySql($sql, array(':user_id' => Yii::app()->user->id));
    	$this->renderPartial('user_profile', array('model' => $model));
    }    

    
    /**
     * Deposit balance
     */
    public function actionDeposit()
    {
        $deposit_history = DepositHistory::getDepositHistoryByUserId(Yii::app()->user->id);
        $this->render('deposit', array('deposit_history'=>$deposit_history));
        //var_dump($deposit_history);
    }

    /**
     * Withdraw balance
     */
    public function actionWithdraw()
    {
        $model = new WithdrawForm();

        $thisuser = User::model()->find('user_id = :user_id',array(':user_id'=>Yii::app()->user->id));
       // var_dump($thisuser->lr_money);
        if (isset($_POST['WithdrawForm']))
        {
        	
            $model->attributes = ($_POST['WithdrawForm']);
            if ($model->validate())
            {
            	if ($model->lr_amnt>$thisuser->lr_money)
            	{
            		Yii::app()->user->setFlash('error', 'Số tiền bạn yêu cầu rút lớn hơn tiền cứng trong tài khoản của bạn. Xin vui lòng kiểm tra lại ');
            	}
                elseif ($this->checkValidCurrency($model->lr_currency))
                {
                    // save table ld_withdraw
                    $withdraw = new Withdraw();
                    $withdraw->request_withdraw_date = date('Y-m-d H:i:s',strtotime('+14 hours'));
                    $withdraw->money = $model->lr_amnt;
                    $withdraw->currency = $model->lr_currency;
                    $withdraw->status = 0;
                    $withdraw->user_id = Yii::app()->user->id;
                    $thisuser->lr_money -= $model->lr_amnt;
                    if ($withdraw->save() && $thisuser->save())
                    {
                    	//$user = User::model()->find('user_id = :user_id',array(':user->id'=>Yii::app()->user->id));
                        Yii::app()->user->setFlash('success', 'Đã đăng ký chuyển tiền. Tiền sẽ về tới tài khoản của bạn trong vòng chậm nhất là 10 phút. Nếu có trục trặc, vui lòng liên hệ với admin qua Yahoo Messenger tại cột bên phải. Thời gian giải quyết chúng tôi đảm bảo không qua 12 giờ ');
                        $this->redirect(Yii::app()->homeUrl.'user/confirmwithdraw');
                    }
                }
                else
                {
                    $model->addError('lr_currency', 'Loại tiền chuyển không hợp lệ');
                }
            }
        }

        // get withdraw history

        $model->withdraw_history = Withdraw::getWithdrawHistoryByUserId(Yii::app()->user->id);

        $this->render('withdraw', array('model' => $model,'maxamount'=>$thisuser->lr_money));
    }

    private function checkValidCurrency($currency)
    {
        $ValidCurrencyList = array('LRUSD');
        return in_array($currency, $ValidCurrencyList);
    }

    /**
     * View history
     */
    public function actionStatistic()
    {
    	$withdraw_history = Withdraw::getWithdrawHistoryByUserId(Yii::app()->user->id);
    	$deposit_history = DepositHistory::getDepositHistoryByUserId(Yii::app()->user->id);
        $lstLoDeHistory = LoDe::layDanhSachLuotChoiCuaNguoiChoi(Yii::app()->user->id);
        $bombhistory = Bomb::bombhistory(Yii::app()->user->id);
        //var_dump($lstLoDeHistory);
        $this->render('statistic', array('lodeHistory'=>$lstLoDeHistory,'bombhistory'=>$bombhistory));
    }
    
    /*
     * confirm withdraw
     */
    
    public function actionconfirmwithdraw()
    {
    	$model = new WithdrawForm();
    	
    	$thisuser = User::model()->find('user_id = :user_id',array(':user_id'=>Yii::app()->user->id));
    	$model->withdraw_history = Withdraw::getWithdrawHistoryByUserId(Yii::app()->user->id);
    	 
    	$this->render('confirmwithdraw', array('model' => $model,'maxamount'=>$thisuser->lr_money));
    }

    /**
     * 
     */
    public function actionIntroduce_Ref()
    {
        $this->render('introduce_ref');
    }


    /**
     * Change password
     */
    public function actionChangePass()
    {
        $model = new ChangePassForm();
        if (isset($_POST['ChangePassForm']))
        {
            $model->attributes = ($_POST['ChangePassForm']);
            $user = User::model()->find('user_id = :user_id', array(':user_id' => Yii::app()->user->id));

            if ($model->validate())
            {
                if (md5($model->current_password) == $user->password)
                {

                    // update password:

                    $user->password = md5($model->new_password);
                    $user->save();

                    // send notice mail
                    //mail($user->email, 'abc', '123');
                    Yii::app()->user->setFlash('success', 'Cáº­p nháº­t máº­t kháº©u thÃ nh cÃ´ng :)');
                    $this->refresh();

                    $model->addError('confirm_password', 'Máº­t kháº©u xÃ¡c nháº­n khÃ´ng Ä‘Ãºng');
                }
                else
                {
                    $model->addError('current_password', 'Máº­t kháº©u hiá»‡n táº¡i khÃ´ng Ä‘Ãºng');
                }
            }
        }
        $this->render('change_password', array('model' => $model));
    }

     /**
     * active account
     */
    public function actionActive()
    {
        $token  = (isset($_GET['token']) && $_GET['token']!=='') ? $_GET['token'] : '';
        if($token !== '')
        {
            $validToken = ValidToken::model()->find('token = :token AND active_reset = :flag', array(':token'=>$token, ':flag'=>  MailUtil::ACTIVE_FLAG));
            if($validToken)
            {
                // Chá»‰ cho active náº¿u token chÆ°a expired
                if($validToken->valid_time > date('Y-m-d H:i:s'))
                {
                    // active tÃ i khoáº£n user
                    $user = User::model()->find('user_id = :user_id', array(':user_id'=>$validToken->user_id));
                    $user->active = 1;
                    if($user->save())
                    {
                        // XÃ³a token Ä‘i
                        $validToken->delete();
                        // KÃ­ch hoáº¡t thÃ nh cÃ´ng
                        $this->layout = '//layouts/main';
                        $this->render('active_success');
                    }
                }
                else
                {
                    // ThÃ´ng bÃ¡o link háº¿t háº¡n
                    $this->render('expired');
                }
            }
        }
    }
    
    public function actionReset()
    {
    	
        $token  = (isset($_GET['token']) && $_GET['token']!=='') ? $_GET['token'] : '';
        
        if($token !== '')
        {
            $validToken = ValidToken::model()->find('token = :token AND active_reset = :flag', array(':token'=>$token, ':flag'=>  MailUtil::RESET_FLAG));
            //var_dump($validToken);
            if($validToken)
            {
                // Náº¿u token Ä‘Ã£ expire thÃ¬ ko cho reset
                if($validToken->valid_time > date('Y-m-d H:i:s'))
                {
                    // Cho user reset password má»›i
                    $model = new RenewPassForm();
                    $model->token = $token;
                    $this->layout = '//layouts/main';
                    $this->render('renew_password', array('model'=>$model));
                }
                else
                {
                    // ThÃ´ng bÃ¡o link háº¿t háº¡n
                    $this->render('expired');
                }
            }
        }
    }
    
    public function actionRenewPassword()
    {
        $model = new RenewPassForm();
        var_dump($_POST['RenewPassForm']);
        if(isset($_POST['RenewPassForm']))
        {
            $model->setAttributes($_POST['RenewPassForm']);
            if($model->validate())
            {
                $validToken = ValidToken::model()->find('token = :token AND active_reset = :flag', array(':token'=>$model->token, ':flag'=>  MailUtil::RESET_FLAG));
                if($validToken)
                {
                    $user = User::model()->find('user_id = :user_id', array(':user_id'=>$validToken->user_id));
                    $user->password = md5($model->new_password);
                    if($user->save())
                    {
                        // XÃ³a token Ä‘i
                        $validToken->delete();
                        // reset máº­t kháº©u thÃ nh cÃ´ng
                        echo 'thanh cong';
                        $this->layout = '//layouts/main';
                        $this->render('renew_success');
                    }
                    
                }
            }
            
        }
        $this->render('renew_password', array('model'=>$model));
    }
}

?>
